<template>
  <view :="fv.rootProps" v-if="state.visible">
    <view :class="[ns.e('bottom')]">
      <Progress :="fv.progressProps" :class="[ns.e('progress')]"/>
      <view :class="[ns.e('copyright')]" v-if="showCopyright">
        <view>{{ t('components.load-page.statement') }}</view>
        <view>{{ t('components.load-page.filings') }}</view>
        <view>{{ t('components.load-page.provider') }}</view>
      </view>
    </view>
  </view>
</template>

<script lang="ts" setup>
import { awaitSetTimeout, useNamespace } from '@/utils'
import LoadPage from '.'
import { computed, onBeforeUnmount, onMounted, reactive } from 'vue'
import Progress from '@/components/progress/index.vue'
import type { Progress as ProgressNameSpace } from '@/components'
import localFile from '@/utils/local-file'
import { t } from '@/locale'
import Timer from '@/utils/timer'

defineOptions({
  name: LoadPage.name
})
const props = defineProps(LoadPage.props)
const emits = defineEmits(LoadPage.emits)
const ns = useNamespace(LoadPage.name)
const config = {
  timer: new Timer('Interval'),
}
const state = reactive({
  progress: <Omit<ProgressNameSpace.Props, 
    keyof (LoadPage.Props['progress'] & {})>>{ total: 100 },
  visible: false,
  showTransition: false
})
const fv = computed(() => {
  const rootProps = {
    class: [
      ns.b,
      state.showTransition && 'is-transition'
    ],
    style: {
      '--load-page-background': `url(${
        localFile.getImage('components/load-page')}) 0 center / cover`,
      '--load-page-transition-duration': LoadPage.variables.transitionTime + 'ms',
      '--load-page-progress-transition-duration': LoadPage.variables.progressTransitionTime + 'ms'
    }
  }
  const progressProps: ProgressNameSpace.Props = {
    showPercentageText: true,
    striped: true,
    stripedFlow: true,
    ...state.progress
  }
  return {
    rootProps,
    progressProps
  }
})

async function startLoad() {
  state.progress.current = 0
  emits('start')
  state.visible = true
  config.timer.stop()
  config.timer.run(() => {
    if (++ state.progress.current! >= (state.progress.total! - 1)) 
      return config.timer.stop()
  }, 50)
  try {
    await props.load()
    emits('success')
  } catch (error) {
    emits('fail', error)
  }
  
  config.timer.stop()
  state.progress.current = state.progress.total

  await awaitSetTimeout(LoadPage.variables.progressTransitionTime)
  
  state.showTransition = true
  
  await awaitSetTimeout(LoadPage.variables.transitionTime)

  state.visible = false
  state.showTransition = false
  emits('complete')
}

onMounted(() => {
  if (props.auto) {
    startLoad()
  }
})
onBeforeUnmount(config.timer.stop)
defineExpose({
  startLoad
})
</script>